<template>
  <!-- 跳过链接 -->
  <a href="#main-content" class="skip-link">跳转到主要内容</a>
  
  <!-- 屏幕阅读器专用内容 -->
  <div class="sr-only" aria-live="polite" id="sr-status"></div>
  
  <!-- 焦点管理 -->
  <div v-if="showFocusIndicator" class="focus-indicator" :style="focusStyle"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const showFocusIndicator = ref(false)
const focusStyle = ref({})

// 焦点管理
const handleFocusIn = (event) => {
  if (event.target.matches('input, button, select, textarea, a, [tabindex]')) {
    const rect = event.target.getBoundingClientRect()
    focusStyle.value = {
      position: 'fixed',
      top: `${rect.top - 2}px`,
      left: `${rect.left - 2}px`,
      width: `${rect.width + 4}px`,
      height: `${rect.height + 4}px`,
      border: '2px solid #409eff',
      borderRadius: '4px',
      pointerEvents: 'none',
      zIndex: 9999
    }
    showFocusIndicator.value = true
  }
}

const handleFocusOut = () => {
  showFocusIndicator.value = false
}

// 键盘导航
const handleKeyDown = (event) => {
  // ESC 键关闭模态框
  if (event.key === 'Escape') {
    const modal = document.querySelector('.el-dialog__wrapper:last-child')
    if (modal) {
      const closeBtn = modal.querySelector('.el-dialog__headerbtn')
      if (closeBtn) closeBtn.click()
    }
  }
  
  // Tab 键循环焦点
  if (event.key === 'Tab') {
    const focusableElements = document.querySelectorAll(
      'input:not([disabled]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])'
    )
    
    if (focusableElements.length === 0) return
    
    const firstElement = focusableElements[0]
    const lastElement = focusableElements[focusableElements.length - 1]
    
    if (event.shiftKey) {
      if (document.activeElement === firstElement) {
        event.preventDefault()
        lastElement.focus()
      }
    } else {
      if (document.activeElement === lastElement) {
        event.preventDefault()
        firstElement.focus()
      }
    }
  }
}

// 屏幕阅读器通知
const announceToScreenReader = (message) => {
  const srStatus = document.getElementById('sr-status')
  if (srStatus) {
    srStatus.textContent = message
    setTimeout(() => {
      srStatus.textContent = ''
    }, 1000)
  }
}

// 检查并修复常见的辅助功能问题
const fixAccessibilityIssues = () => {
  // 为没有 alt 属性的图片添加默认值
  const images = document.querySelectorAll('img:not([alt])')
  images.forEach(img => {
    img.setAttribute('alt', '图片')
  })
  
  // 为没有 title 的按钮添加 aria-label
  const buttons = document.querySelectorAll('button:not([aria-label]):not([title])')
  buttons.forEach(btn => {
    if (!btn.textContent.trim()) {
      btn.setAttribute('aria-label', '按钮')
    }
  })
  
  // 为表单元素添加 name 属性
  const formElements = document.querySelectorAll('input:not([name]):not([id]), select:not([name]):not([id]), textarea:not([name]):not([id])')
  formElements.forEach((element, index) => {
    element.setAttribute('name', `field_${index}`)
  })
  
  // 为框架添加 title
  const frames = document.querySelectorAll('iframe:not([title])')
  frames.forEach(frame => {
    frame.setAttribute('title', '嵌入内容')
  })
  
  // 修复 aria-hidden 元素中的可聚焦元素
  const hiddenElements = document.querySelectorAll('[aria-hidden="true"]')
  hiddenElements.forEach(element => {
    const focusableChildren = element.querySelectorAll('button, input, select, textarea, a, [tabindex]')
    focusableChildren.forEach(child => {
      child.setAttribute('tabindex', '-1')
    })
  })
  
  // 为 div 上的 aria-label 添加 role
  const divWithAriaLabel = document.querySelectorAll('div[aria-label]:not([role])')
  divWithAriaLabel.forEach(div => {
    div.setAttribute('role', 'region')
  })
}

// 监听路由变化，更新页面标题和焦点
const handleRouteChange = () => {
  // 更新页面标题
  const routeName = window.location.pathname.split('/').pop() || 'home'
  document.title = `${routeName} - 洗衣店用户端`
  
  // 将焦点移到主要内容区域
  const mainContent = document.getElementById('main-content')
  if (mainContent) {
    mainContent.focus()
    announceToScreenReader(`已导航到 ${routeName} 页面`)
  }
}

onMounted(() => {
  // 添加事件监听器
  document.addEventListener('focusin', handleFocusIn)
  document.addEventListener('focusout', handleFocusOut)
  document.addEventListener('keydown', handleKeyDown)
  
  // 初始修复
  fixAccessibilityIssues()
  
  // 监听 DOM 变化
  const observer = new MutationObserver(() => {
    setTimeout(fixAccessibilityIssues, 100)
  })
  
  observer.observe(document.body, {
    childList: true,
    subtree: true
  })
  
  // 监听路由变化
  window.addEventListener('popstate', handleRouteChange)
  
  // 暴露全局方法
  window.announceToScreenReader = announceToScreenReader
})

onUnmounted(() => {
  document.removeEventListener('focusin', handleFocusIn)
  document.removeEventListener('focusout', handleFocusOut)
  document.removeEventListener('keydown', handleKeyDown)
  window.removeEventListener('popstate', handleRouteChange)
})
</script>

<style scoped>
.skip-link {
  position: absolute;
  top: -40px;
  left: 6px;
  background: #000;
  color: #fff;
  padding: 8px;
  text-decoration: none;
  z-index: 9999;
  border-radius: 4px;
}

.skip-link:focus {
  top: 6px;
}

.focus-indicator {
  transition: all 0.1s ease;
}

.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
</style>
